/*
 * Copyright (c) 2010, Nikolaus Moll
 * All rights reserved.
 */
package net.miblounge.gradecalculator.guicommon.widgets;

import java.util.LinkedList;
import java.util.List;

import net.miblounge.gradecalculator.core.enums.ExaminationType;
import net.miblounge.gradecalculator.core.enums.ExaminationTypeList;
import net.miblounge.gradecalculator.guicommon.interfaces.IValidationListener;

import com.trolltech.qt.gui.QWidget;

public class PerformancesSelector extends MultiComboBox {
	
	public PerformancesSelector(final QWidget parent)
	{
		super(parent, getValues());

		final IValidationListener parentListener = getParentListener(parent);
		if (parentListener != null) { 
			addValidationListener(parentListener);
		}
		
		notifyValidate();
	}
	
	private static IValidationListener getParentListener(final QWidget parent)
	{
		QWidget current = parent;
		while (current != null) {
			if (current instanceof IValidationListener) {
				return (IValidationListener)current;
			}
			
			current = current.parentWidget();
		}
		
		return null;
	}	

	private static List<String> getValues()
	{
		final List<String> result = new LinkedList<String>();
		for (final ExaminationType type : ExaminationType.values()) {
			result.add(getText(type));
		}
		return result;
	}
	
	private static String getText(final ExaminationType type) {
		return type.getAbbreviation() + " - " + type.getName();
	}
	
	public ExaminationTypeList getPerformances()
	{
		final ExaminationTypeList result = new ExaminationTypeList(); 
		final List<String> selectedItems = super.getSelectedItems();
		for (final String item : selectedItems) {
			final ExaminationType type = ExaminationType.valueOf(item);
			if (type != null) {
				result.add(type);
			}
		}
		
		return result;
	}

	public void setPerformances(final ExaminationTypeList values) {
		final List<String> selectedItems = new LinkedList<String>();
		for (ExaminationType value : values) {
			selectedItems.add(getText(value));
		}
		
		super.setSelectedItems(selectedItems);
	}

}
